<template>
  <!-- 全部患者详情 -->
  <div class="allPatientDetails">
    <div class="allPatientDetails-left">
      <div class="patient-search" @click="handleGo">
        <el-icon><user /></el-icon>搜索患者
      </div>
      <div :class="{'item-active': isActive === p.customerId}" class="person-item" v-for="p in historyList" :key="p.customerId">
        <div class="avarat">
          <avaratImg :age="p.age" :customerSex="p.customerSex"></avaratImg>
        </div>
        <span class="person-name" @click="handleGoDetails(p)"><a href="javascript:;">{{p.customerName}}</a></span>
        <span>{{p.from ? ('('+p.from+')') : ''}}</span>
        <span
          v-for="icon in p.showRules"
          class="circular-icon p0"
          :key="icon.id"
          :class="{'bg-blue': icon.showType === '蓝色'}"
          >{{icon.showLabel}}</span>
          <span class="circular-icon p0 bg-red" v-if="p.hasArrearsOrder" >欠</span>
        <div class="delete-item" @click="handleDelectItem(p.customerId)"><el-icon><delete /></el-icon></div>
        <div class="register-item" @click="handleToRegister(p.customerId)" >
          <abbr title="挂号" style="text-decoration: none; font-weight: bold;">
            <i class="iconfont icon-jinru_huabanfuben"></i>
          </abbr>
        </div>
      </div>
    </div>
    <div class="allPatientDetails-right">
      <el-card class="manage">
        <div class="header">
          <zpersonInfo ref="personInfoRef" :id="userId" @getPersonName="getPersonName"></zpersonInfo>
        </div>
        <div class="main" >
          <!-- <el-tabs v-model="activeName" @tab-click="handleClick">
              <template v-for="i in tabItemList" >
                <el-tab-pane

                  :label="i.label"
                  :name="i.name"
                  v-jurisdiction="i.role"
                  >
                  </el-tab-pane>
              </template>


          </el-tabs> -->

          <el-scrollbar class="scroll-height">
            <div class="cortom-tabs">
              <div class="tab-item"
                :class="activeName === '1'? 'active' : ''"
                @click="handleClick('1')">{{'患者信息'}}</div>
              <div class="tab-item"
                :class="activeName === i.name ? 'active' : ''"
                v-for="i in tabItemList"
                :key="i.componentName"
                v-jurisdiction="i.role"
                @click="handleClick(i.name)">{{i.label}}</div>
            </div>
          </el-scrollbar>

          <div class="router-view-page">
            <router-view v-slot="{Component}">

              <component :is="Component" />


            </router-view>
          </div>
        </div>
      </el-card>
    </div>
  </div>




  <!-- 预约 -->
    <el-drawer
			size="42%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
      <zaddpatient
            @cancel="cancel"
            @saveMakeAnAppointment="saveMakeAnAppointment"
            @saveAndRegister="saveAndRegister"
            v-if="isADD === 'add'"
      ></zaddpatient>
      <zregister v-if="isADD === 'register'"
          @cancel="cancel"
          :userId="PersonId"
      ></zregister>
      <zmakeanapp
        v-if="isADD === 'makeanapp'"
        @handlebtn="handlebtn"
        @cancel="cancel"
        :personName="personName"
      ></zmakeanapp>
    </el-drawer>

</template>

<script lang="ts">
import { User, Delete} from '@element-plus/icons-vue'
import { defineComponent, reactive, toRefs, ref, onMounted, inject, onUnmounted, computed, watch, watchEffect, nextTick } from "vue";
import zpersonInfo from "../../components/styleBorder/personInfo.vue";
import useRequet, { RespData } from "../../hook/network"

import zmakeanapp from "../../components/patient/makeAnAppointment.vue"
import zaddpatient from "../../components/patient/add.vue"
import zregister from "../../components/patient/register.vue"

import avaratImg from "../../components/avatarImg/avatarImg.vue"

import { ElMessage, ElMessageBox } from 'element-plus'
import { HistoryList } from "../../types/index"

import { useRoute, useRouter } from "vue-router"

export default defineComponent({
  name:'allPatientDetails',
  components: {
    zpersonInfo,
    avaratImg,

    zmakeanapp,
    zaddpatient,
    zregister,

    User, Delete
  },
  setup() {
    const route= useRoute()
    const router = useRouter()
    const request = useRequet({ path: "" });
    const isSelf = ref(route.query.my)
    const userId= ref<any>(route.params.id)

    // const jurisdictionList =

    watch(() => route.params.id, (newID) => {
        userId.value = newID
        if(!newID) {
          window.localStorage.removeItem('activeName')
        }
    })

    const isActive = ref(-1)
    const list = reactive({
      activeName: '1',
    })

    const tabItemList = [
      // {
      //   label: '患者信息',
      //   name: '1',
      //   // role: '',
      //   componentName: 'patient'
      // },
      {
        label: '就诊记录',
        name: '2',
        role: 'customer:record:detail:list',
        componentName: 'Record'
      },
      {
        label: '会员信息',
        name: '3',
        role: 'customer:account:view',
        componentName: 'Member'
      },
      {
        label: '诊疗费用',
        name: '10',
        role: 'customer:order:save',
        componentName: 'PriceSet'
      },
      {
        label: '收费',
        name: '4',
        role: 'customer:order:show',
        componentName: 'ChargeModel'
      },
      {
        label: '电子病历',
        name: '5',
        role: 'customer:sick:history:show',
        componentName: 'MedicalRecord'
      },
      {
        label: '影像',
        name: '6',
        role: 'customer:sick:image:show',
        componentName: 'Image'
      },
      {
        label: '随访',
        name: '7',
        role: 'customer:access:follow:show',
        componentName: 'FollowUp'
      },
      {
        label: '回访',
        name: '8',
        role: 'customer:access:visit:show',
        componentName: 'Returnvisit'
      },
      {
        label: '技加工',
        name: '9',
        role: 'warehouse:process:list',
        componentName: 'Machin'
      }
    ]

    watchEffect(() => {

      if(route.params.id) {
        if(route.query.type) {
          list.activeName = route.query.type as string
        } else {
          list.activeName = window.localStorage.getItem('activeName') || '1'
        }

        }

    })

    const personInfoRef = ref<any>(null)
    // 刷新患者信息
    const refreshInfo = () => {
      personInfoRef.value.getCustomerInfo()
    }

    const personName = ref('')
    let historyList = ref([] as HistoryList[])

    const getPersonName = (person: string) => {
      personName.value = person
    }

    // 回到患者
    const handleGo = () => {
      if(isSelf.value) {
        router.push({name:'MyPatients'})
      } else {
        router.push({name:'AllPatients'})
      }

    }
    // 跳转详情
    const handleGoDetails = (Data: HistoryList) => {
      isActive.value = Data.customerId
      let id = Data.customerId;

      let fullPath = route.fullPath;
      let full = fullPath.split('/')[2]
      let first = fullPath.split('/')[1]
      let last = fullPath.split('/')[3]
      if(last.includes('?')) {
        last = last.split('?')[0]
      }
      let newPath = `/${first}/${id}/${last}`

      console.log(newPath)
      router.push(newPath)
    }
    const getHistoryList = () => {
      request.sendRequest({
        address: 'customer/info/getSelectLogPage',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取历史患者' + resp.msg )
					historyList.value = resp.data.records

        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取历史患者' + resp.msg )

        },
        method: "POST",
      })
    }
    getHistoryList()

    const handleDelectItem = (id: number) => {
      request.sendRequest({
        address: `customer/info/deleteSelectLogByCustomerId/${id}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('患者' + resp.msg )
          getHistoryList()
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('患者' + resp.msg )

        },
        method: "POST",
      })
    }

    const PersonId = ref()
    // 去挂号
    const handleToRegister = (id: number) => {
      PersonId.value = id
      isADD.value = 'register'
			title.value = "挂号"
      showDrawer.value = true
    }

    // 新建预约部分
    const showDrawer = ref(false)
    const title = ref('新建预约')
    const isADD = ref('')
    // 打开新建预约
    const saveMakeAnAppointment = () => {
      isADD.value = 'makeanapp'
			title.value = "新建预约"
    }

    const saveAndRegister = () => {
			isADD.value = 'register'
			title.value = "挂号"
		}


    const handlebtn = () => {
      isADD.value = 'add'
			title.value = "个人信息"
    }
    const drawerClose = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }
    const cancel = () => {
      showDrawer.value = false
    }

    // 切换
    const handleClick = (type: string) => {
      list.activeName = type;
      window.localStorage.setItem('activeName', String(type))
      switch(type) {
        case '1':
          router.push({name: 'Patient'})
          break;
        case '2':
          router.push({name: 'Record'})
          break;
        case '3':
          router.push({name: 'Member'})
          break;
        case '4':
          router.push({name: 'ChargeModel'})
          break;
        case '5':
          router.push({name: 'MedicalRecord'})
          break;
        case '6':
          router.push({name: 'Image'})
          break;
        case '7':
          router.push({name: 'FollowUp'})
          break;
        case '8':
          router.push({name: 'Returnvisit'})
          break;
        case '9':
          router.push({name: 'Machin'})
          break;
        case '10':
          router.push({name: 'PriceSet'})
          break;
      }
    }

    return {
      userId,
      tabItemList,
      ...toRefs(list),
      getPersonName,
      personName,
      isActive,

      refreshInfo,
      personInfoRef,

      PersonId,
      handleToRegister,
      showDrawer,
      title,
      isADD,
      saveMakeAnAppointment,
      saveAndRegister,
      handlebtn,
      drawerClose,
      cancel,

      handleGo,
      handleGoDetails,
      handleClick,

      handleDelectItem,
      historyList,
    }
  }
})
</script>

<style lang="scss" scoped>

.allPatientDetails {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  .allPatientDetails-left {
    width: 15%;
    height: 100%;
    background: white;

    .patient-search {
      height: 45px;
      width: 100%;
      line-height: 45px;
      text-align: center;
      background: white;
      color: $mainColor;
      cursor: pointer;
      border-bottom: 1px solid #E4E7ED;
      box-sizing: border-box;

      & > i {
        padding-right: 5px;
        color: $mainColor;
      }
    }

    .person-item {
      display: flex;
      align-items: center;
      height: 45px;
      line-height: 45px;
      border-bottom: 1px solid #E4E7ED;
      cursor: pointer;
      position: relative;

      .avarat {
        height: 100%;
        & > span {
          margin: 2px;
          width: 40px;
          height: 40px;
        }
      }

      .icon {
        width: 32px;
        height: 32px;
        padding-left: 10px;
      }

      .person-name {
        padding: 0 10px;
      }

      & > span {
        & > a {
          text-decoration: none;
          color: $primaryText;
        }
      }
      .p0 {
        padding: 0;
      }

      .delete-item {
        position: absolute;
        right: 0px;
        padding: 0 10px;
        display: none;
      }

      .register-item {
        position: absolute;
        right: 30px;
        display: none;
      }

    }
    .person-item:hover {
      border:1px solid $mainColor;
      background: white;
      color: $mainColor;

      & > .delete-item {
        display: block;
      }

      & > .register-item {
        display: block;
      }

      & > span > a {
        text-decoration: underline;
        color: $mainColor;
      }
    }
  }

  .allPatientDetails-right {
    width: calc(100% - 15%);
    height: 100%;
  }
}
.scroll-height {
  height: 40px;
}

.cortom-tabs {
  display: flex;
  align-content: center;
  min-width: 800px;
  border-bottom: 2px solid $mainColor;
  box-sizing: border-box;

  .tab-item {
    padding: 10px 20px;
    border-right: 1px solid $mainColor;
    box-sizing: border-box;
    white-space: nowrap;

    font-size: 13px;
    cursor: pointer;
  }
  .tab-item:hover {
    background-color: $mainColor;
    color: #fff;
  }
}

.item-active {
  background-color: #f5f6f7;
}
</style>
